package com.lagou.api;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.CountDownLatch;

/**
 * @param null
 * @author oyz
 * @version 1.0
 * @description: 创建节点
 * @date 2022/2/25 9:26
 */
public class CreateNode implements Watcher {


    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    private static ZooKeeper zooKeeper;

    /**
     * 客户端可以通过创建⼀个zk实例来连接zk服务器
     * new Zookeeper(connectString,sesssionTimeOut,Wather)
     * connectString: 连接地址：IP：端⼝
     * sesssionTimeOut：会话超时时间：单位毫秒
     * Wather：监听器(当特定事件触发监听时，zk会通过watcher通知到客户端)
     */


    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        zooKeeper = new ZooKeeper("192.168.106.128:2181", 5000, new CreateNode());
        System.out.println(zooKeeper.getState());


        System.out.println("客户端与服务端建立连接成功...");
        Thread.sleep(Integer.MAX_VALUE);


    }

    /**
     * path ：节点创建的路径
     * data[] ：节点创建要保存的数据，是个byte类型的
     * acl ：节点创建的权限信息(4种类型)
     * ANYONE_ID_UNSAFE : 表示任何⼈
     * AUTH_IDS ：此ID仅可⽤于设置ACL。它将被客户机验证的ID替
     * 换。
     * OPEN_ACL_UNSAFE ：这是⼀个完全开放的ACL(常⽤)-->
     * world:anyone
     * CREATOR_ALL_ACL ：此ACL授予创建者身份验证ID的所有权限
     * createMode ：创建节点的类型(4种类型)
     * PERSISTENT：持久节点
     * PERSISTENT_SEQUENTIAL：持久顺序节点
     * EPHEMERAL：临时节点
     * EPHEMERAL_SEQUENTIAL：临时顺序节点
     * String node = zookeeper.create(path,data,acl,createMode);
     */
    private static void createNodeSync() throws UnsupportedEncodingException, KeeperException, InterruptedException {
        String node_PERSISTENT = zooKeeper.create("/lg_persistent", "持久节点内容".getBytes("utf-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        String node_PERSISTENT_SEQUENTIAL = zooKeeper.create("/lg_ephemeral_sequential", "持久节点内容".getBytes("utf-8"),ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
        String node_EPERSISTENT = zooKeeper.create("/lg_ephemeral", "临时节点内容".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println("创建的持久节点是:"+node_PERSISTENT);
        System.out.println("创建的持久顺序节点是:"+node_PERSISTENT_SEQUENTIAL);
        System.out.println("创建的临时节点是:"+node_EPERSISTENT);
    }

    /**
     * 回调方法：处理来自服务器端的watcher通知
     *
     * @param watchedEvent
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        //当连接创建了，服务端发送给客户端SyncConnected事件
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {

            // 创建节点
            try {
                createNodeSync();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
